import com.rslai.commons.util.FileUtil;

import java.io.*;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 图片资源查找
 * Created by rslai on 2018/12/8.
 */
public class FindResource {
    String resTypePattern = ".*(?i)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|webp|jfif|tiff|dib).*"; // 资源文件（图片）类型

    /**
     * 图片资源查找
     * @param findFiles
     */
    public void findResource(List<String> findFiles) {
        for (String findFile : findFiles) {
            oneFindResource(findFile);
        }
    }

    /**
     * 在一个app中查找资源
     *
     * @param fileName
     */
    private void oneFindResource(String fileName) {
        String destPath = new FileUtil().getCanonicalPath(fileName).replace(".ipa", "").replace(".apk", "");

        FileUtil fileUtil = new FileUtil();
        List<String> fileList = fileUtil.listAll(destPath);

        StringBuffer sb = new StringBuffer();
        sb.append(htmlHead(5));
        for (String name : fileList) {
            if (resType(name)) {
                sb.append("<li><img src=\"file://" + name + "\" alt=\"" + name + "\"/></li>\r\n");
            }
        }
        sb.append(htmlfooter());

        String resFileName = destPath + "_res.html";

        try {
            fileUtil.write(resFileName, sb.toString());
            System.out.println("查找图片资源成功，详情查看（建议使用ie查看，部分图片可能在chrome中显示错误）：         " + resFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成html头
     * @param col 几列
     * @return
     */
    private String htmlHead(int col) {
        int width = (100-(col+1))/col;
        return ("<html>\n" +
                "<head>\n" +
                "<meta charset=\"utf-8\">\n" +
                "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0\">\n" +
                "<title>三列图片等宽布局</title>\n" +
                "<style>\n" +
                "* {\n" +
                "    margin: 0;\n" +
                "    padding: 0;\n" +
                "}\n" +
                "li {\n" +
                "\ttext-align: center;\n" +
                "    display: block;\n" +
                "    width: " + width + "%;\n" +
                "    margin: 1% 0 0 1%;\n" +
                "    float: left;\n" +
                "    border: solid 1px red;\n" +
                "}\n" +
                "img {\n" +
                "    max-width: 100%;\n" +
                "    max-height: 100%;\n" +
                "}" +
                "</style>\n" +
                "</head>\n" +
                "<body>\n" +
                "<div>");
    }

    /**
     * 生成html脚注
     * @return
     */
    private String htmlfooter() {
        return ("</div>   \n" +
                "</body>\n" +
                "</html>");
    }

    /**
     * 判断文件是否是图片文件
     * @param str 文件名
     * @return {@code true} 是图片
     */
    private boolean resType(String str) {
        return Pattern.matches(resTypePattern, str);
    }

}


